package com.yanqu.road.web.controller.usercenter;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.web.HttpJsonWebParam;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.web.WebServer;
import com.yanqu.road.web.controller.BaseJsonHttpServlet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/platformQueryUnionDetailInfo")
public class PlatformQueryUnionDetailInfo extends BaseJsonHttpServlet {

    private static Logger logger = LogManager.getLogger(PlatformQueryUnionDetailInfo.class.getName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.info("request platformQueryUnionDetailInfo");
        HttpJsonWebParam httpJsonWebParam = super.parseRequest(request);
        JSONObject paramObj = httpJsonWebParam.getParamObj();
        int serverId;
        try{
            serverId = paramObj.getIntValue("server_id");
        }catch (Exception e){
            logger.error("platformQueryUnionDetailInfo argument error:" + e);
            sendResult(response, 0, "argument error");
            return;
        }
        if(WebServer.getInstance().isNeedSend() && ServerListMgr.isCnMergeServer(serverId)){
            // 转发消息到对应的服务器上
            String result = HttpHelper.doPostJson(ChannelConfig.LOGIN_SEND_URL + "platformQueryUnionDetailInfo", paramObj.toJSONString(), "UTF-8");
            sendMessage(response, result);
            return;
        }
        ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
        if (serverInfo == null) {
            logger.error("platformQueryUnionDetailInfo no find serverId:{}", serverId);
            sendResult(response, 0, "serverId no exist");
            return;
        }

        // 转发消息到对应的服务器上
        String result = HttpHelper.doPostJson(serverInfo.getWebServerUrl() + "/queryUnionDetailInfo", paramObj.toJSONString(), "UTF-8");
        sendMessage(response, result);
    }
}
